package com.module.netty.channel;

import com.module.common.utils.HexUtils;
import com.module.common.utils.StringUtils;
import com.module.netty.listener.NettyListener;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Slf4j
@Component
@SuppressWarnings("unchecked")
public class NettyChannel {

    // channel连接组
    private static ChannelGroup GlobalGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    //定义channelid 的map信息
    private static ConcurrentMap<String, ChannelId> ChannelMap = new ConcurrentHashMap();

    /**
     * 保存channel信息
     * @param channel
     */
    public void addChannel(Channel channel){
        GlobalGroup.add(channel);
        ChannelMap.put(channel.id().asLongText(), channel.id());
    }

    public void addChannel(Channel channel, String host, int port) {
        GlobalGroup.add(channel);
        ChannelMap.put(channel.id().asLongText(), channel.id());
    }

    /**
     * 移除channel信息
     * @param channel
     */
    public void removeChannel(Channel channel){
        GlobalGroup.remove(channel);
        ChannelMap.remove(channel.id().asLongText());
    }

    /**
     * 将数据发送到tcp客户端
     * @param id
     * @param receiveStr
     * @param mark
     */
    public void writeToClient(String id, String receiveStr, String mark) {
        ChannelId channelId = ChannelMap.get(id);
        if(receiveStr.contains(" ")){
            receiveStr = receiveStr.replace(" ", "");
        }
        Channel channel = GlobalGroup.find(channelId);
        if(StringUtils.isNotNull(channel)) {
            ByteBuf bufff = Unpooled.buffer();//netty需要用ByteBuf传输
            bufff.writeBytes(HexUtils.hexString2Bytes(receiveStr));//对接需要16进制
            //如果通道处于活动状态并且已连接
            if (channel.isActive() && channel.isWritable()) {
                channel.writeAndFlush(bufff).addListener(new NettyListener(id, receiveStr, mark));
            }
        }
    }
}
